﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.DataAccess.Trademark.Interfaces;
using AMS.DataAccess.Trademark.BO;
using System.Data;
using AMS.DataAccess.Trademark.BO.Enums;
using AMS.DataAccess.Trademark.Filters;
using AMS.DataAccess;
using AMS.DataAccess.Filter;

public partial class Task_CheckTask : BaseWorkPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DoDataBind();
        }
        else
        {
            LoadPostBackData();
        }
    }

    private void LoadPostBackData()
    {
        hfSelectedTaskID.Value = Request[hfSelectedTaskID.UniqueID];
        hfCheckNote.Value = Request[hfCheckNote.UniqueID];
    }

    #region DataBind and pager events
    TaskFilter filter;
    private void DoDataBind()
    {
        int total = 0;
        ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
        if (filter == null)
        {
            GetTaskFilter();
        }

        List<TaskInfo> taskList = taskMgr.GetPagedTaskList(CallContext, filter, pager.CurrentPageIndex, pager.PageSize, out total);
        gv.DataSource = taskList;
        gv.DataKeyNames = new string[] { "AID", "Status" };
        gv.DataBind();
        BindPager(total);

        int newTaskCount = 0;
        int unFinishedTaskCount = 0;
        DataTable dtSummary = taskMgr.GetMyTaskSummaryByStatus(CallContext, false);
        foreach (DataRow row in dtSummary.Rows)
        {
            int status = (int)row["Status"];
            if (status == (int)TaskStatus.NewTask)
            {
                newTaskCount += (int)row["StatusCount"];
                unFinishedTaskCount += (int)row["StatusCount"];
            }
            else if (status == (int)TaskStatus.UnCompleted)
            {
                unFinishedTaskCount += (int)row["StatusCount"];
            }
        }

        lblTotal.Text = total.ToString();
    }

    void BindPager(int totalCount)
    {
        pager.RecordCount = totalCount;
        pager2.RecordCount = totalCount;
    }

    protected string FormatDateTime(object value, bool includeTime)
    {
        return Utils.FormateDateTime(value, includeTime);
    }

    protected void pager_PageChanged(object sender, EventArgs e)
    {
        DoDataBind();
    }

    protected void pager2_PageChanged(object sender, EventArgs e)
    {
        DoDataBind();
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        DoDataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        DoDataBind();
    }
    #endregion

    void GetTaskFilter()
    {
        filter = new TaskFilter();
        filter.QueryClosedTask = true;
        if (chkCheckedTask.Checked)
        {
            filter.StatusList.Add(TaskStatus.Checked);
            filter.StatusList.Add(TaskStatus.Closed);
        }
        else
        {
            filter.StatusList.Add(TaskStatus.Completed);
        }

        if (!string.IsNullOrEmpty(txtCaseIndex.Text))
        {
            filter.CaseIndex = new StringFilterField(txtCaseIndex.Text);
        }
        if (!string.IsNullOrEmpty(txtTaskName.Text))
        {
            filter.CaseIndex = new StringFilterField(txtTaskName.Text, StringOperations.Like);
        }

        DateTime dt = DateTime.Now;
        DateTime dtCompared = DateTime.MinValue;
        if (drpStartTime.SelectedIndex > 0)
        {
            if (drpStartTime.SelectedIndex == 1)
            {
                dtCompared = dt;
            }
            else if (drpStartTime.SelectedIndex == 2)
            {
                dtCompared = dt.AddDays(-3);
            }
            else if (drpStartTime.SelectedIndex == 3)
            {
                int daysToMonday = (int)dt.DayOfWeek - (int)DayOfWeek.Monday;
                dtCompared = dt.AddDays(0 - daysToMonday);
            }
            else
            {
                dtCompared = dt.AddDays(0 - dt.Day);
            }

            filter.StartDate = new DateTimeFilterField(dtCompared, DateTimeType.Date, SqlOperations.LargerThanOrEquals);
        }
        if (!(chkHigh.Checked && chkLow.Checked && chkNormal.Checked))
        {
            if (chkHigh.Checked) filter.Priorities.Add(TaskPriority.High);
            if (chkNormal.Checked) filter.Priorities.Add(TaskPriority.Normal);
            if (chkLow.Checked) filter.Priorities.Add(TaskPriority.Low);
        }
    }

    void BatchCheckTasks()
    {
        List<int> selectedIDs = GetCheckItemIDs();
        ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
        int count = taskMgr.BatchCheckTask(CallContext,
            selectedIDs.ToArray(),
            hfCheckNote.Value);

        if (selectedIDs.Count == count)
        {
            MsgInfo(string.Format("审核{0}项任务。", count));
        }
        else
        {
            MsgWarning(string.Format("成功{0}, 失败{1}。<br/>失败原因：任务可能被删除。",
                count,
                selectedIDs.Count - count));
        }

        if (count > 0)
        {
            DoDataBind();
        }
    }

    List<int> GetCheckItemIDs()
    {
        List<int> ids = new List<int>();
        foreach (GridViewRow row in gv.Rows)
        {
            CheckBox chk = row.FindControl("chk") as CheckBox;
            if (chk.Checked)
            {
                int id = Convert.ToInt32(gv.DataKeys[row.RowIndex].Values["AID"]);
                ids.Add(id);
            }
        }

        return ids;
    }

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow)
        {
            return;
        }

        LinkButton lk = e.Row.FindControl("lkCheck") as LinkButton;
        int statusCode = Convert.ToInt32(gv.DataKeys[e.Row.RowIndex].Values["Status"]);
        if (statusCode == (int)TaskStatus.Checked || statusCode == (int)TaskStatus.Closed)
        {
            lk.Text = "取消审核";
            lk.OnClientClick = "javascript:if(!confirm('取消审核将删除审核消息，确定吗？')){event.cancelBubble = true; return false;}";
        }
        else
        {
            lk.Text = "审核";
            lk.Attributes["href"] = "javascript:void(0);";
            lk.Attributes["onclick"] = "javascript:checkTask(" + DataBinder.Eval(e.Row.DataItem, "AID") + "); event.cancelBubble = true; return false;";
        }
    }

    protected void btnCheckTask_Command(object sender, CommandEventArgs e)
    {
        int taskId = 0;
        int.TryParse(hfSelectedTaskID.Value, out taskId);
        ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
        if (taskId == -1)
        {
            BatchCheckTasks();
        }
        else
        {
            taskMgr.CheckTask(CallContext, taskId, hfCheckNote.Value);
            DoDataBind();
        }

        MsgInfo("审核成功。");
    }


    protected void lkCheck_Command(object sender, CommandEventArgs e)
    {
        int taskId = Convert.ToInt32(e.CommandArgument);
        ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
        taskMgr.CancelCheckTask(CallContext, taskId);
        MsgInfo("设定成功。");
        DoDataBind();
    }
}
